import logging
from datetime import datetime

from sqlalchemy import Integer, Column, String, Float, Date, DateTime, JSON, TEXT, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Query, Session

from py_engine import engine

logger = logging.getLogger(__name__)

Base = declarative_base(bind=engine)


class User(Base):
    __table_args__ = {'extend_existing': True}
    __tablename__ = 'user'

    # 主键，自增
    user_id = Column('user_id', Integer(), primary_key=True, autoincrement=True)
    # 非空，唯一，索引
    user_name = Column('user_name', String(length=32), nullable=False, unique=True, index=True)
    # 更新列
    update_column = Column('update_column', Float(), nullable=False, default=0.0)
    # 生日：日期格式
    user_birthday = Column('user_birthday', Date(), nullable=False, default=datetime.now().date())
    # 默认值，更新触发赋值
    update_datetime = Column('update_datetime', DateTime(), default=datetime.now(), onupdate=datetime.now())

    json_column = Column('json_column', JSON(), nullable=True, default='')
    text_column = Column('text_column', TEXT(), nullable=True, default='')


class TableModel(Base):
    __table__ = Table('table_name', Base.metadata, autoload=True, autoload_with=engine)


def py_query():
    _Session = sessionmaker(bind=engine)
    session: Session = _Session()
    # result = session.query(TableModel)

    query: Query = session.query(TableModel)
    query: Query = query.filter(TableModel.column_name != 'chench111').filter_by(column_pk=2)

    data = query.all()
    data = session.query(TableModel).all()
    for item in data:
        logger.info()
    session.close()


if __name__ == '__main__':
    """创建表，初始化数据"""
    # Base.metadata.create_all()

    py_query()
